<template>
  <ContentWrap>
    <!-- 搜索工作栏 -->
    <el-form
      class="-mb-15px"
      :model="queryParams"
      ref="queryFormRef"
      :inline="true"
      label-width="80px"
    >
      <!-- 第一行 -->
      <el-row :gutter="16">
        <el-col :span="6">
          <el-form-item 
            label="客户名称:" 
            prop="personName"
          >
            <el-input
              v-model="queryParams.personName"
              placeholder="请输入客户名称"
              clearable
              @keyup.enter="handleQuery"
              class="!w-240px"
            />
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item 
            label="国家地区:" 
            prop="country"
          >
            <el-input
              v-model="queryParams.country"
              placeholder="请输入国家地区"
              clearable
              @keyup.enter="handleQuery"
              class="!w-240px"
            />
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item 
            label="客户优先级:" 
            label-width="90px" 
            prop="priorityCode"
          >
            <el-select
              v-model="queryParams.priorityCode"
              placeholder="请选择客户优先级"
              clearable
              class="!w-240px"
            >
              <el-option
                v-for="item in priorityCode"
                :key="item"
                :label="item"
                :value="item"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item 
            label="客户状态:" 
            prop="statusCode"
          >
            <el-select
              v-model="queryParams.statusCode"
              placeholder="请选择客户状态"
              clearable
              class="!w-240px"
            >
              <el-option
                v-for="item in statusCode"
                :key="item"
                :label="item"
                :value="item"
              />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>

      <!-- 第二行 -->
      <el-row :gutter="16">
        <el-col :span="6">
          <el-form-item 
            label="行业分类:" 
            prop="industryCode"
          >
            <el-select
              v-model="queryParams.industryCode"
              placeholder="请选择行业分类"
              clearable
              class="!w-240px"
            >
              <el-option
                v-for="item in industryCode"
                :key="item"
                :label="item"
                :value="item"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item 
            label="客户来源:" 
            prop="sourceCode"
          >
            <el-select
              v-model="queryParams.sourceCode"
              placeholder="请选择客户来源"
              clearable
              class="!w-240px"
            >
              <el-option
                v-for="item in sourceCode"
                :key="item"
                :label="item"
                :value="item"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item>
            <el-button style="margin-left: 40px;" type="primary" @click="handleQuery">
               查询
            </el-button>
            <el-button
                  @click="resetQuery" style="
                  background-color: transparent;
                  border: 1px solid #409eff;
                  color: #409eff;
                "
                plain 
                type="primary">
              重置
            </el-button>
          </el-form-item>
        </el-col>
      </el-row>

      <!-- 第三行   
           <Icon icon="ep:edit" class="mr-5px" />
             <Icon icon="ep:delete" class="mr-5px" />
               <Icon icon="ep:user" class="mr-5px" />
                 <Icon icon="ep:share" class="mr-5px" />-->
      <el-row>
        <el-col :span="24">
          <el-form-item>
            <el-button
              type="primary"
              
              @click="openForm('create')"
              v-hasPermi="['business:cust-info:create']"
            >
               新增
            </el-button>
            <el-button 

               style="
                  background-color: transparent;
                  border: 1px solid #409eff;
                  color: #409eff;
                "
                plain 
                type="primary"
              
              @click="openStatusChangeDialog" 
              v-hasPermi="['business:cust-info:update']"
            >
               修改客户状态
            </el-button>
            <el-button
              @click="handleReleaseToSea"
              :disabled="!selectedRowKeys.length"
              v-hasPermi="['business:cust-info:delete']"
               style="
                  background-color: transparent;
                  border: 1px solid #409eff;
                  color: #409eff;
                "
                plain 
                type="primary"
            >
               释放到公海
            </el-button>
            <el-button
              style="
                  background-color: transparent;
                  border: 1px solid #409eff;
                  color: #409eff;
                "
                plain 
                type="primary"
              
              @click="handleChangeSalesman"
              v-hasPermi="['business:cust-info:update']"
            >
               修改业务员
            </el-button>
            <el-button
              style="
                  background-color: transparent;
                  border: 1px solid #409eff;
                  color: #409eff;
                "
                plain 
                type="primary"
              
              @click="handleTransfer"
              v-hasPermi="['business:cust-info:update']"
            >
               交接
            </el-button>
            <el-button
              style="
                  background-color: transparent;
                  border: 1px solid #409eff;
                  color: #409eff;
                "
                plain 
                type="primary"
              
              @click="handleBatchDelete"
              :disabled="!selectedRowKeys.length"
              v-hasPermi="['business:cust-info:delete']"
            >
               删除
            </el-button>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
  </ContentWrap>

  <!-- 列表 -->
  <ContentWrap>
    <el-table
      v-loading="loading"
      :data="list"
      :stripe="true"
      :show-overflow-tooltip="true"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55"  />
        <el-table-column type="index"  align="center" label="序号" width="60px" />
      <el-table-column 
        label="客户编码" 
        align="center" 
        prop="code" 
      />
      <el-table-column 
        label="客户名称" 
        align="center"
      >
        <template #default="scope">
          <span 
            class="link-type" 
            style="color: blue; cursor: pointer;" 
            @click="handleNameClick(scope.row)"
          >
            {{ scope.row.personName || scope.row.companyName }}
          </span>
        </template>
      </el-table-column>
      <el-table-column 
        label="国家地区" 
        align="center" 
        prop="country" 
      />
      <el-table-column 
        label="客户来源" 
        align="center" 
        prop="sourceCode" 
      />
      <el-table-column 
        label="客户状态" 
        align="center" 
        prop="statusCode" 
      />
      <el-table-column 
        label="客户优先级" 
        align="center" 
        prop="priorityCode" 
      />
      <el-table-column 
        label="客户星级" 
        align="center" 
        prop="starCode" 
      />
      <el-table-column 
        label="行业分类" 
        align="center" 
        prop="industryCode" 
      />
      <el-table-column 
        label="所属业务员" 
        align="center" 
        prop="salesman" 
      />
      <el-table-column 
        label="客户阶段" 
        align="center" 
        prop="stageCode" 
      />
    </el-table>
    <!-- 分页 -->
    <Pagination
      :total="total"
      v-model:page="queryParams.pageNo"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />
  </ContentWrap>

  <!-- 表单弹窗：添加/修改 -->
  <CustInfoForm
    ref="formRef" 
    @success="getList" 
    :stage-codes="stageCode"
    :star-codes="starCode"
    :industry-codes="industryCode"
    :status-codes="statusCode"
    :source-codes="sourceCode"
    :priority-codes="priorityCode"
  />

  <el-dialog
  v-model="changeSalesmanDialogVisible"
  title="修改业务员"
  width="600px"
  destroy-on-close
>
  <!-- 搜索框 -->
  <el-row :gutter="10" align="middle" class="search-box">
  <el-col :span="6">
    <div class="label-text">归属业务员:</div>
  </el-col>
  <el-col :span="18">
    <el-input
      v-model="searchSalesmanText"
      placeholder="搜索业务员名称:"
      clearable
      @input="handleSalesmanSearch"
    >
      <template #prefix>
        <el-icon><Search /></el-icon>
      </template>
    </el-input>
  </el-col>
</el-row>

  <!-- 树结构 -->
  <el-tree
    ref="salesmanTreeRef"
    :data="filteredSalesmanTree"
    :props="{ label: 'label', children: 'children' }"
    node-key="id"
    highlight-current
    :filter-node-method="filterSalesmanNode"
    :default-expand-all="true"
    @node-click="handleSalesmanNodeClick"
    class="salesman-tree"
  />

  <template #footer>
    <el-button @click="changeSalesmanDialogVisible = false">取消</el-button>
    <el-button type="primary" :disabled="!selectedSalesmanId" @click="submitChangeSalesman">确定</el-button>
  </template>
</el-dialog>

  <!-- 修改客户状态弹窗组件 -->
  <el-dialog 
    v-model="dialogVisible" 
    title="修改客户状态" 
    width="30%"
  >
    <div style="padding: 10px">
      <el-row>
        <el-col :span="6" style="line-height: 40px">客户状态:</el-col>
        <el-col :span="18">
          <el-select
            v-model="selectedStatus"
            placeholder="请选择状态"
            :disabled="loadingDialog"
          >
            <el-option
              v-for="item in statusOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-col>
      </el-row>
    </div>

    <template #footer>
      <div style="text-align: right; padding: 10px">
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button 
          type="primary" 
          @click="confirmStatusChange" 
          :loading="loadingDialog"
        >
          确定
        </el-button>
      </div>
    </template>
  </el-dialog>

  <!-- 释放到公海弹窗 -->
  <el-dialog 
    v-model="releaseDialogVisible" 
    title="释放到公海" 
    width="30%"
  >
  <!--
  如果要添加表单验证需要在以下位置,加入以下代码
   首先要添加ref动态绑定
  ref="releaseFormRef"
  当然了需要在script setup中添加releaseFormRef动态变量
  其次需要在script setup中添加释放规则
  随后在提交逻辑submitRelease中手动触发表单验证
  releaseRules -->
    <el-form 
    ref="releaseFormRef" 
    :model="releaseForm"
    :rules="releaseRules"
    label-width="80px"
    >
      <el-form-item label="释放原因" prop="releaseReason">
        <el-input
          v-model="releaseForm.releaseReason"
          type="textarea"
          :rows="3"
          placeholder="请输入释放原因"
          maxlength="300"
          show-word-limit
        />
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="releaseDialogVisible = false">取消</el-button>
      <el-button type="primary" @click="submitRelease">确定</el-button>
    </template>
  </el-dialog>

    <el-dialog
    v-model="handoverSalesmanDialogVisible"
    title="客户交接"
    width="600px"
    destroy-on-close
  >
    <!-- 搜索框 -->
    <el-row :gutter="10" align="middle" class="search-box">
      <el-col :span="6">
        <div class="label-text">接收业务员:</div>
      </el-col>
      <el-col :span="18">
        <el-input
          v-model="searchSalesmanText"
          placeholder="搜索业务员名称:"
          clearable
          @input="handleSalesmanSearch"
        >
          <template #prefix>
            <el-icon><Search /></el-icon>
          </template>
        </el-input>
      </el-col>
    </el-row>

    <!-- 树结构 -->
    <el-tree
      ref="salesmanTreeRef"
      :data="filteredSalesmanTree"
      :props="{ label: 'label', children: 'children' }"
      node-key="id"
      highlight-current
      :filter-node-method="filterSalesmanNode"
      :default-expand-all="true"
      @node-click="handleSalesmanNodeClick"
      class="salesman-tree"
    />

    <template #footer>
      <el-button @click="handoverSalesmanDialogVisible = false">取消</el-button>
      <el-button type="primary" :disabled="!handoverSalesmanId" @click="submitHandoverSalesman">
        确定
      </el-button>
    </template>
  </el-dialog>

</template>

<script setup lang="ts">
const currentCustomerId = ref<number | null>(null)
//import { ref, reactive, onMounted } from 'vue'
import { ref, onMounted } from 'vue'
import { useMessage } from '@/hooks/web/useMessage'
import { useI18n } from '@/hooks/web/useI18n'
import { ElMessage, ElTree } from 'element-plus'
//import { ElMessage } from 'element-plus'
import { insertCustToHighSeas } from '@/api/customermanager/custmanage'
import { CustInfoApi, CustInfoVO } from '@/api/customermanager/custmanage'
import CustInfoForm from './CustInfoForm.vue'
import { useRouter } from 'vue-router'
import { Search } from '@element-plus/icons-vue'
import { ElMessageBox } from 'element-plus';
//import CustInfoApi from '@/api/customermanager/custmanage'

const releaseFormRef = ref()
const releaseRules = reactive({
  releaseReason: [
    { required: true, message: '释放原因为必填项', trigger: 'blur' } // 失焦触发验证
  ]
})
const handoverSalesmanDialogVisible = ref(false)
const handoverSalesmanId = ref<number | null>(null)
const handoverDialogVisible = ref(false)
const handoverTargetId = ref<number | null>(null)
const changeSalesmanDialogVisible = ref(false)
const currentSalesmanName = ref('')
const selectedSalesmanId = ref<number | null>(null)
const salesmanTreeData = ref([])
const { t } = useI18n()
const message = useMessage()
const router = useRouter()

const salesmanDialogVisible = ref(false)
const searchSalesmanText = ref('')
const salesmanTree = ref([])
const filteredSalesmanTree = ref<any[]>([])
const selectedSalesman = ref<any>(null)
const salesmanTreeRef = ref<InstanceType<typeof ElTree>>()
const treeKey = ref(0)

// 数据状态
const loading = ref(true)
const list = ref<CustInfoVO[]>([])
const total = ref(0)
const selectedRowKeys = ref<number[]>([])
const selectedSingleId = ref<number | null>(null)
const queryFormRef = ref()

const submitreleaseReason = async () => {
  // 手动触发表单验证
  const valid = await releaseFormRef.value.validate().catch(() => false)
  if (!valid) return

  try {
    await insertCustToHighSeas({
      ids: selectedRowKeys.value,
      releaseReason: releaseForm.releaseReason
    })

    ElMessage.success('释放成功')
    releaseDialogVisible.value = false
    releaseForm.releaseReason = ''
    selectedRowKeys.value = []

    await getList()
  } catch (error) {
    ElMessage.error('释放失败，请稍后重试')
  }
}
const submitHandoverSalesman = async () => {
  if (!handoverSalesmanId.value) {
    return ElMessage.warning('请选择新业务员')
  }

  try {
    await CustInfoApi.updateSalesman({
      ids: selectedRowKeys.value,
      salesmanId: handoverSalesmanId.value
    })
    ElMessage.success('客户交接成功')
    handoverSalesmanDialogVisible.value = false
    selectedRowKeys.value = []
    await getList()
  } catch (e) {
    console.error('交接失败:', e)
    ElMessage.error('交接失败: ' + (e.message || '未知错误'))
  }
}
// 处理树节点点击
const handleSalesmanNodeClick = (node: any) => {
  // 只允许选择用户节点（叶子节点），不允许选择部门节点
  if (!node.children || node.children.length === 0) {
    // 判断当前是修改业务员还是交接
    if (changeSalesmanDialogVisible.value) {
      selectedSalesmanId.value = node.id
    } else if (handoverSalesmanDialogVisible.value) {
      handoverSalesmanId.value = node.id
    }
  } else {
    // 清空选择（如果点击的是部门节点）
    if (changeSalesmanDialogVisible.value) {
      selectedSalesmanId.value = null
    } else if (handoverSalesmanDialogVisible.value) {
      handoverSalesmanId.value = null
    }
    ElMessage.warning('请选择具体的业务员（用户节点）')
  }
}
const handleSalesmanSearch = () => {
  if (salesmanTreeRef.value) {
    salesmanTreeRef.value.filter(searchSalesmanText.value)
  }
}

const filterSalesmanNode = (value: string, data: any) => {
  if (!value) return true
  return data.label.includes(value)
}

const handleSalesmanSelect = (node: any) => {
  if (!node.children) {
    selectedSalesman.value = node
  } else {
    selectedSalesman.value = null // 只允许选择用户，不允许选部门
  }
}

const confirmSalesman = async () => {
  if (!selectedSalesman.value) {
    return ElMessage.warning('请选择业务员')
  }

  if (!currentCustomerId.value) {
    return ElMessage.error('未找到客户 ID，无法提交')
  }

  try {
    await CustInfoApi.updateSalesman({
      customerId: currentCustomerId.value,
      salesmanId: selectedSalesman.value.id
    })
    ElMessage.success('业务员修改成功')
    salesmanDialogVisible.value = false
    await getList() // ✅ 直接刷新列表数据
  } catch (err) {
    console.error('修改失败', err)
    ElMessage.error('修改失败')
  }
}

const handleOpenSalesmanDialog = (row: CustInfoVO) => {
  currentCustomerId.value = row.id
  salesmanDialogVisible.value = true
  loadSalesmanTree()
}

const handleTransfer = async () => {
  if (selectedRowKeys.value.length === 0) {
    return ElMessage.warning('请至少选择一条数据')
  }

  handoverSalesmanId.value = null

  try {
    await loadSalesmanTree() // ✅ 保证树数据加载完
    handoverSalesmanDialogVisible.value = true

    nextTick(() => {
      if (salesmanTreeRef.value) {
        salesmanTreeRef.value.filter(searchSalesmanText.value)
      }
    })
  } catch (e) {
    ElMessage.error('加载组织架构失败')
  }
}

// 提交交接
const submitHandover = async () => {
  if (!handoverTargetId.value) {
    return ElMessage.warning('请选择新业务员')
  }
  try {
    await CustInfoApi.updateSalesman({
      ids: selectedRowKeys.value,
      salesmanId: handoverTargetId.value.id
    })
    ElMessage.success('客户交接成功')
    handoverDialogVisible.value = false
    selectedRowKeys.value = []
    getList()
  } catch (error) {
    ElMessage.error('交接失败，请稍后重试')
  }
}

// 查询参数
const queryParams = reactive({
  pageNo: 1,
  pageSize: 10,
  personName: undefined,
  country: undefined,
  sourceCode: undefined,
  industryCode: undefined,
  priorityCode: undefined,
  statusCode: undefined
})

// 弹窗相关
const dialogVisible = ref(false)
const releaseDialogVisible = ref(false)
const loadingDialog = ref(false)
const statusLoaded = ref(false)
const selectedStatus = ref<string | number>('')
const statusOptions = ref<{ label: string; value: string | number }[]>([])
const releaseForm = reactive({
  releaseReason: ''
})

// 下拉选项
const stageCode = ref<string[]>([])
const starCode = ref<string[]>([])
const industryCode = ref<string[]>([])
const statusCode = ref<string[]>([])
const sourceCode = ref<string[]>([])
const priorityCode = ref<string[]>([])

// 表单引用
const formRef = ref()

/** 查询列表 */
const getList = async () => {
  loading.value = true
  try {
    const data = await CustInfoApi.getCustInfoPage(queryParams)
    list.value = data.list
    total.value = data.total
  } finally {
    loading.value = false
  }
}

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.pageNo = 1
  getList()
}

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value.resetFields()
  handleQuery()
}

/** 添加/修改操作 */
const openForm = (type: string, id?: number) => {
  formRef.value.open(type, id)
}

/** 表格选中处理 */
const handleSelectionChange = (selection: CustInfoVO[]) => {
  selectedRowKeys.value = selection.map(item => item.id)
  selectedSingleId.value = selection.length > 0 ? selection[0].id : null
}

/** 确认修改客户状态 */
const confirmStatusChange = async () => {
  if (!selectedStatus.value) {
    message.warning('请选择客户状态')
    return
  }

  try {
    await CustInfoApi.setCustStatusById(selectedSingleId.value!, selectedStatus.value)
    message.success('客户状态修改成功')
    dialogVisible.value = false
    await getList()
  } catch (error) {
    message.error('修改失败，请重试')
  }
}

/** 打开修改客户状态弹窗 */
const openStatusChangeDialog = async () => {
  if (!selectedSingleId.value) {
    message.warning('请先选择一条数据')
    return
  }

  loadingDialog.value = true

  if (!statusLoaded.value) {
    try {
      const data = await CustInfoApi.getCustStatusList()

      if (!Array.isArray(data)) {
        throw new Error('接口返回的数据不是数组')
      }

      const uniqueData = [...new Set(data)]

      statusOptions.value = uniqueData.map((name) => ({
        label: name,
        value: name
      }))

      statusLoaded.value = true
    } catch (error) {
      message.error('获取客户状态失败')
      console.error('加载客户状态失败:', error)
      loadingDialog.value = false
      return
    }
  }

  loadingDialog.value = false
  dialogVisible.value = true
}

/** 释放到公海操作 */
const handleReleaseToSea = () => {
  if (!selectedRowKeys.value.length) {
    ElMessage.warning('请至少选择一个客户')
    return
  }
  releaseDialogVisible.value = true
}

/** 提交释放到公海 */
const submitRelease = async () => {
  if (!releaseForm.releaseReason) {
    ElMessage.error('释放原因不能为空')
    return
  }

  try {
    await insertCustToHighSeas({
      ids: selectedRowKeys.value,
      releaseReason: releaseForm.releaseReason
    })

    ElMessage.success('释放成功')
    releaseDialogVisible.value = false
    releaseForm.releaseReason = ''
    selectedRowKeys.value = []

    await getList()
  } catch (error) {
    ElMessage.error('释放失败，请稍后重试')
  }
}

// 在 loadSalesmanTree 中处理 null children
const normalizeTreeChildren = (nodes: any[]) => {
  return nodes.map(node => {
    // 确保 children 是数组
    const children = node.children 
      ? normalizeTreeChildren(node.children) 
      : [];
    
    return {
      ...node,
      children
    };
  });
}
const normalizeTreeData = (nodes: any[]): any[] => {
  return nodes.map(node => ({
    id: node.id,
    label: node.label,
    children: Array.isArray(node.children) ? normalizeTreeData(node.children) : []
  }))
}

const loadSalesmanTree = async () => {
  try {
    const apiResponse = await CustInfoApi.getSalesmanTree()
    
    // 解构时使用默认值和别名
    const {
      code: statusCode = -1,
      data: responseData = null,
      result: apiResult = null
    } = apiResponse
    
    // 处理不同响应结构
    let finalData = null
    
    if (Array.isArray(apiResponse)) {
      // 如果响应直接是数组
      console.info("响应直接是数组")
      finalData = apiResponse
    } else if (Array.isArray(responseData)) {
      // 标准结构: {code, data}
      console.info("标准结构: {code, data}")
      finalData = responseData
    } else if (apiResult && Array.isArray(apiResult.data)) {
      // 嵌套结构: {result: {code, data}}
      console.info("嵌套结构: {result: {code, data}}")
      finalData = apiResult.data
    } else if (Array.isArray(apiResponse.data)) {
      // 兼容直接返回 {data: [...]}
      console.info("兼容直接返回 {data: [...]}")
      finalData = apiResponse.data
    }

    console.log('树结构数据:', finalData)
    
    if (finalData) {
      filteredSalesmanTree.value = finalData
      console.log("组织架构数据:", finalData)
    } else {
      console.error("无法识别的响应结构:", apiResponse)
      ElMessage.error("组织架构数据格式异常")
    }
    
    treeKey.value++
  } catch (error) {
    console.error('加载失败:', error)
    ElMessage.error(`加载失败: ${error.message || '未知错误'}`)
  }
}

// 自动选择当前业务员（优化版）
const autoSelectCurrentSalesman = () => {
  const traverse = (nodes: any[]): boolean => {
    for (const node of nodes) {
      // 只匹配用户节点（叶子节点）
      if ((!node.children || node.children.length === 0) && 
          node.label === currentSalesmanName.value) {
        selectedSalesmanId.value = node.id;
        // 设置当前选中节点（需要等待DOM更新）
        nextTick(() => {
          salesmanTreeRef.value?.setCurrentKey(node.id);
        });
        return true;
      }
      // 递归遍历子节点
      if (node.children && traverse(node.children)) {
        return true;
      }
    }
    return false;
  };

  traverse(filteredSalesmanTree.value);
};
/** 修改业务员 */
const handleChangeSalesman = async () => {
  if (selectedRowKeys.value.length === 0) {
    return message.warning('请至少选择一条数据')
  }

  const selectedSalesmen = list.value
    .filter(item => selectedRowKeys.value.includes(item.id))
    .map(item => item.salesman)

  const uniqueSalesmen = [...new Set(selectedSalesmen)]

  if (uniqueSalesmen.length > 1) {
    // 显示弹窗提示
    ElMessageBox.alert(
      '当前所选的客户属于多个业务员，不允许批量修改业务员',
      '提示',
      {
        confirmButtonText: '确定',
        type: 'info',
      }
    );
    return;
    //return ElMessage.error('所选客户属于多个业务员，不允许批量修改')
  }

  currentSalesmanName.value = uniqueSalesmen[0] || ''
  selectedSalesmanId.value = null

  // 🌟 只有组织树为空时才加载
  if (!salesmanTreeData.value.length) {
    try {
      await loadSalesmanTree()
    } catch (e) {
      ElMessage.error('加载组织架构失败')
      return
    }
  }
  searchSalesmanText.value = currentSalesmanName.value
  changeSalesmanDialogVisible.value = true
  autoSelectCurrentSalesman()
  handleSalesmanSearch()
}



// 提交修改业务员请求
const submitChangeSalesman = async () => {
  if (!selectedSalesmanId.value) {
    return ElMessage.warning('请选择业务员');
  }

  try {
    // 调用后端API
    await CustInfoApi.updateSalesman({
      ids: selectedRowKeys.value,        // 选中的客户ID数组
      salesmanId: selectedSalesmanId.value // 选中的业务员ID
    });
    console.log("selectedSalesmanId.value"+selectedSalesmanId.value)

    
    ElMessage.success('业务员修改成功');
    changeSalesmanDialogVisible.value = false;
    selectedRowKeys.value = [];
    await getList(); // 刷新列表
  } catch (e) {
    console.error('修改业务员失败', e);
    ElMessage.error('修改失败: ' + (e.message || '未知错误'));
  }
};

/** 批量删除 */
const handleBatchDelete = async () => {
  if (selectedRowKeys.value.length === 0) {
    message.warning('请至少选择一条数据')
    return
  }
  
  try {
    await message.delConfirm('确定删除选中的客户吗？')
    
    // 记录成功和失败的删除
    let successCount = 0
    let failCount = 0
    
    // 循环调用单个删除接口
    for (const id of selectedRowKeys.value) {
      try {
        await CustInfoApi.deleteCustInfo(id)
        successCount++
      } catch (error) {
        console.error(`删除ID为${id}的客户失败:`, error)
        failCount++
      }
    }
    
    // 根据结果显示提示
    if (failCount === 0) {
      message.success(`成功删除${successCount}个客户`)
    } else if (successCount === 0) {
      message.error(`删除${failCount}个客户全部失败`)
    } else {
      message.warning(`成功删除${successCount}个客户，${failCount}个删除失败`)
    }
    
    // 刷新列表
    await getList()
    selectedRowKeys.value = []
  } catch (error) {
    if (error !== 'cancel') {
      message.error('删除过程中出现错误')
      console.error('批量删除出错:', error)
    }
  }
}

/** 客户名称点击跳转 */
const handleNameClick = (row: CustInfoVO) => {
  router.push({
    name: 'CustFollow', // 使用路由名称代替路径
    query: { 
      cust_id: row.id,
      cust_name: row.personName || row.companyName,
      type_code: row.typeCode
    }
  })
}

/** 加载所有下拉选项数据 */
const loadAllDropdownOptions = async () => {
  try {
    const [
      stageData,
      starData,
      industryData,
      statusData,
      sourceData,
      priorityData
    ] = await Promise.all([
      CustInfoApi.getStageCode(),
      CustInfoApi.getStarCode(),
      CustInfoApi.getIndustryCode(),
      CustInfoApi.getStatusCode(),
      CustInfoApi.getSourceCode(),
      CustInfoApi.getPriorityCode()
    ])

    stageCode.value = Array.isArray(stageData) ? stageData : []
    starCode.value = Array.isArray(starData) ? starData : []
    industryCode.value = Array.isArray(industryData) ? industryData : []
    statusCode.value = Array.isArray(statusData) ? statusData : []
    sourceCode.value = Array.isArray(sourceData) ? sourceData : []
    priorityCode.value = Array.isArray(priorityData) ? priorityData : []

  } catch (error) {
    console.error('加载下拉选项失败:', error)
  }
}

/** 初始化 */
onMounted(() => {
  getList()
  loadAllDropdownOptions()
  loadSalesmanTree()
})
</script>

<style scoped>
.salesman-tree {
  max-height: 300px;
  overflow-y: auto;
  margin-top: 10px;
  border: 1px solid #ebeef5;
  padding: 8px;
  border-radius: 4px;
}
.search-box {
  display: flex;
  margin-bottom: 10px;
}

.label-text {
  font-weight: bold;
  line-height: 32px; /* 与输入框高度对齐 */
  text-align: right;
}


</style>